<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}
/*
 * 微信登录API
 */

class loginApi {

    const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
    const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
    const OAUTH_TOKEN_URL = '/access_token?';
    const OAUTH_REFRESH_URL = '/refresh_token?';
    const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';

    private $city_id;
	private $corpid;
    private $corpsecret;
	private $agentid;
	private $userId;
    private $userToken;
    public $scope = 'snsapi_userinfo';
    public $errCode = 0;
    public $errMsg = 'no access';

    public function __construct($city_id) {
        $setting = F('steward/setting_city_' . $city_id);
		if(isHave($setting['corp_info'])){
			$setting=$setting['corp_info'];
			if (isHave($setting['corpSecret']) && isHave($setting['corpID'])) {
				$this->city_id = $city_id;
				$this->corpid = $setting['corpID'];
				$this->corpsecret =  $setting['corpSecret'];
				$this->agentid = $setting['agentId'];
			} else {
				showError('api Error:请设置CorpId、CorpSecret'); 
			}
		}else{
			showError('api Error:请设置CorpId、CorpSecret'); 
		}

    }

    /**
     * oauth 授权跳转接口
     * @param string $callback 回调URI
     * @return string
     */
    public function getOauthRedirect($callback, $scope = 'base') {
        if ($scope == 'base') {
            $this->scope = 'snsapi_base';
            $state = 1;
        } else {
            $this->scope = 'snsapi_userinfo';
            $state = 2;
        }
//        echo $this->scope;exit;
        return self::OAUTH_PREFIX . self::OAUTH_AUTHORIZE_URL . 'appid=' . $this->corpid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $this->scope . '&state=' . $state . '#wechat_redirect';
    }

    /*
     * 通过code获取Access Token
     * @return array {accessToken,expires_in,refresh_token,openid,scope}
     */

    public function getOauthAccessToken($code = '', $state = 1) {
        $state = ($state == 2) ? 2 : 1;
        if (!$code || $code == 'authdeny') {//禁止授权
            $this->errCode = -1;
            $this->errMsg = '用户未授权';
            return false;
        }
        $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $this->corpid . '&corpsecret=' . $this->corpsecret);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = '未授权-' . $json['errmsg'];
                return false;
            }
			$this->userToken = $json['access_token'];
			$result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$json['access_token'].'&code='.$code.'&agentid='.$this->agentid);
			if ($result) {
				$json = json_decode($result, true);
				if (!$json || !empty($json['errcode'])) {
					$this->errCode = $json['errcode'];
					$this->errMsg = '未授权-' . $json['errmsg'];
					return false;
				}
				$this->userId = $json['UserId'];
				if ($state == 2) {
					$json = $this->getOauthUserinfo();
				}
				$json['state'] = $state;
				return $json;
			}
        }
        return false;
    }

    /**
     * 获取授权后的用户资料
     * @param string $accessToken
     * @param string $openid
     * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege}
     */
    private function getOauthUserinfo() {
        if (!$this->userToken || !$this->userId) {
            $this->errCode = -2;
            $this->errMsg = '未授权或者openid丢失';
            return false;
        }
        $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=' . $this->userToken . '&userid=' . $this->userId);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

}
